'use strict';

const Controller = require('egg').Controller;

class AddressController extends Controller {

  async insert() {
    const { ctx } = this;
    const userInfo = ctx.userInfo;
    // try {
    await ctx.service.car.insert({
      ...ctx.request.body,
      user_id: userInfo.id,
    });
    ctx.body = {
      code: 1,
      message: '加入成功',
    };
    // } catch (e) {
    //   ctx.throw(422, '创建失败');
    // }
  }

  async remove() {
    const { ctx } = this;
    try {
      await ctx.service.address.remove(ctx.params.id);
      ctx.body = {
        code: 1,
        message: '删除成功',
      };
    } catch (e) {
      ctx.throw(422, '删除失败');
    }
  }

  async update() {
    const { ctx } = this;
    try {
      await ctx.service.car.update(ctx.request.body);
      ctx.body = {
        code: 1,
        message: '更新成功',
      };
    } catch (e) {
      ctx.throw(422, '更新失败');
    }
  }

  async show() {
    const { ctx } = this;
    const res = await ctx.service.address.get(ctx.params.id);
    ctx.body = {
      code: 1,
      data: {
        ...res,
        location: JSON.parse(res.location),
      },
    };
  }

  async list() {
    const { ctx } = this;
    const userInfo = ctx.userInfo;
    const res = await ctx.service.car.select(userInfo.id);
    ctx.body = {
      code: 1,
      data: res,
    };
  }

}

module.exports = AddressController;
